package com.example.newsSys.listener;

import jakarta.servlet.ServletContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Enumeration;
// springboot上下文监听器 可获得ApplicationContext进行资源的初始化
@Component
public class MyServletContextListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 获取当前项目的ApplicationContext对象
        ApplicationContext context = event.getApplicationContext();
        // 获取当前项目的ServletContext对象
        ServletContext servletContext = context.getBean(ServletContext.class);
        /*
        // 查看当前项目ServletContext对象中的所有属性
        Enumeration<String> names = servletContext.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            System.out.println(name);
        }
        */

        /*
        // 遍历输出当前项目所有的spring容器管理的bean
        String[] names1 = context.getBeanDefinitionNames();
        for (String name : names1) {
            System.out.println(name);
        }*/
    }
}
